package cn.rwklyd.BookKeeping.service.impl;

import cn.rwklyd.BookKeeping.constant.MessageConstant;
import cn.rwklyd.BookKeeping.mapper.mybatisPlus.BudgetMapper;
import cn.rwklyd.BookKeeping.pojo.Budget;
import cn.rwklyd.BookKeeping.pojo.Result;
import cn.rwklyd.BookKeeping.service.BudgetService;
import cn.rwklyd.BookKeeping.util.UserUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

@Service
@Slf4j
public class BudgetServiceImpl extends ServiceImpl<BudgetMapper, Budget> implements BudgetService {

    @Autowired
    private BudgetMapper budgetMapper;

    @Override
    @Transactional
    public Result<String> addBudget(Budget budget) {
        // 获取当前用户ID
        Long userId = UserUtils.getCurrentUserId();
        if (userId == null) {
            return Result.error(MessageConstant.USER_NOT_LOGIN);
        }
        
        // 参数验证
        if (budget.getAmount() == null) {
            return Result.error("预算金额不能为空");
        }
        
        if (budget.getAmount().doubleValue() <= 0) {
            return Result.error("预算金额必须大于0");
        }
        
        if (budget.getCreateTime() == null) {
            return Result.error("预算日期不能为空");
        }
        
        // 设置用户ID
        budget.setUserId(userId);
        
        // 获取预算日期所在的年月
        int year = budget.getCreateTime().getYear();
        int month = budget.getCreateTime().getMonthValue();
        
        log.info("创建预算: 用户ID={}, 金额={}, 年={}, 月={}, 创建时间={}", 
                 userId, budget.getAmount(), year, month, budget.getCreateTime());
        
        try {
            // 先查询所有预算，检查是否有问题
            LambdaQueryWrapper<Budget> allQuery = new LambdaQueryWrapper<>();
            allQuery.eq(Budget::getUserId, userId)
                    .eq(Budget::getStatus, 1);
            List<Budget> allBudgets = budgetMapper.selectList(allQuery);
            
            log.info("用户{}共有{}个预算", userId, allBudgets.size());
            for (Budget b : allBudgets) {
                log.info("已有预算: ID={}, 金额={}, 创建时间={}, 年={}, 月={}", 
                         b.getId(), b.getAmount(), b.getCreateTime(), 
                         b.getCreateTime().getYear(), b.getCreateTime().getMonthValue());
            }
            
            // 检查是否已存在相同年月的预算
            LambdaQueryWrapper<Budget> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Budget::getUserId, userId)
                       .eq(Budget::getStatus, 1);
            
            // 使用函数提取年月进行比较
            queryWrapper.apply("YEAR(create_time) = {0}", year)
                       .apply("MONTH(create_time) = {0}", month);
            
            // 打印SQL语句
            String sql = queryWrapper.getCustomSqlSegment();
            log.info("查询SQL片段: {}", sql);
            
            // 查询是否已存在预算
            List<Budget> existingBudgets = budgetMapper.selectList(queryWrapper);
            log.info("查询到{}年{}月已有{}个预算", year, month, existingBudgets.size());
            
            for (Budget b : existingBudgets) {
                log.info("冲突预算: ID={}, 金额={}, 创建时间={}", 
                         b.getId(), b.getAmount(), b.getCreateTime());
            }
            
            if (!existingBudgets.isEmpty()) {
                log.info("用户{}在{}年{}月已存在预算，不能重复创建", userId, year, month);
                return Result.error("当前年月已存在预算，不能重复创建");
            }
            
            // 设置默认值
            budget.setUpdateTime(LocalDateTime.now());
            budget.setStatus(1); // 默认启用
            
            // 保存预算
            boolean success = this.save(budget);
            if (success) {
                log.info("用户{}创建{}年{}月预算成功，ID={}", userId, year, month, budget.getId());
                return Result.success("创建预算成功");
            } else {
                log.error("用户{}创建{}年{}月预算失败", userId, year, month);
                return Result.error("创建预算失败");
            }
        } catch (Exception e) {
            log.error("创建预算异常: {}", e.getMessage(), e);
            return Result.error("创建预算失败: " + e.getMessage());
        }
    }

    @Override
    @Transactional
    public Result<String> deleteBudget(Long id) {
        Long userId = UserUtils.getCurrentUserId();
        if (userId == null) {
            return Result.error(MessageConstant.USER_NOT_LOGIN);
        }
        
        Budget budget = this.getById(id);
        if (budget == null) {
            return Result.error("预算不存在");
        }
        
        if (!budget.getUserId().equals(userId)) {
            return Result.error("无权操作此预算");
        }
        
        // 逻辑删除，将status设为0
        budget.setStatus(0);
        budget.setUpdateTime(LocalDateTime.now());
        
        boolean success = this.updateById(budget);
        if (success) {
            return Result.success("删除预算成功");
        } else {
            return Result.error("删除预算失败");
        }
    }

    @Override
    @Transactional
    public Result<String> updateBudget(Budget budget) {
        Long userId = UserUtils.getCurrentUserId();
        if (userId == null) {
            return Result.error(MessageConstant.USER_NOT_LOGIN);
        }
        
        if (budget.getId() == null) {
            return Result.error("预算ID不能为空");
        }
        
        if (budget.getAmount() != null && budget.getAmount().doubleValue() <= 0) {
            return Result.error("预算金额必须大于0");
        }
        
        Budget old = this.getById(budget.getId());
        if (old == null) {
            return Result.error("预算不存在");
        }
        
        if (!old.getUserId().equals(userId)) {
            return Result.error("无权操作此预算");
        }
        
        // 保留原创建时间
        budget.setCreateTime(old.getCreateTime());
        budget.setUpdateTime(LocalDateTime.now());
        
        boolean success = this.updateById(budget);
        if (success) {
            return Result.success("更新预算成功");
        } else {
            return Result.error("更新预算失败");
        }
    }

    @Override
    public Result<Budget> getBudgetById(Long id) {
        Long userId = UserUtils.getCurrentUserId();
        if (userId == null) {
            return Result.error(MessageConstant.USER_NOT_LOGIN);
        }
        
        Budget budget = this.getById(id);
        if (budget == null || budget.getStatus() == 0) {
            return Result.error("预算不存在");
        }
        
        if (!budget.getUserId().equals(userId)) {
            return Result.error("无权查看此预算");
        }
        
        return Result.success(budget);
    }

    @Override
    public Result<List<Budget>> getBudgetsByYearMonth(Integer year, Integer month) {
        Long userId = UserUtils.getCurrentUserId();
        if (userId == null) {
            return Result.error(MessageConstant.USER_NOT_LOGIN);
        }
        
        log.info("查询用户{}在{}年{}月的预算", userId, year, month);
        
        LambdaQueryWrapper<Budget> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Budget::getUserId, userId)
                   .eq(Budget::getStatus, 1)
                   .apply("YEAR(create_time) = {0}", year)
                   .apply("MONTH(create_time) = {0}", month)
                   .orderByDesc(Budget::getCreateTime);
        
        List<Budget> budgets = this.list(queryWrapper);
        log.info("查询到{}条预算记录", budgets.size());
        
        return Result.success(budgets);
    }
} 